% To calculate casuallity analysis of up- and downgrade std
% transition prob (cohort method) of G1000k annual data
% Reference: de Meulemeester, J.-L., and D. Rochat. 1995. A causality analysis of the link between higher education and economic development. Economics of Education Review 14 (4):351-361.



clear all;
clc;
load Prob_std_TP06YRJfinR5G1000kMR7.mat
% GDP = xlsread('D:\My Documents\CIRANO\Stata\GDP_Canada_yr.xlsx','c9:c20'); 
GDP = xlsread('D:\My Documents\CIRANO\Stata\GDP_Canada_quarter.xlsx','c16:c63');
TM =zeros(12,7,8); % take the needed data from prob_std. totaly 12yrs from 1998-2009. 7 ratings and 8 columns including default
TM(:,:,1:7)=prob_std(2:13,3:9,3:9);
TM(:,:,8)=prob_std(2:13,3:9,11);

TimeLength = size(TM,1);
RateSize = size(TM,2);


% up- and downgrade prob involving a migration of at most two buckets
% downgrade porb: d(k,t) = p(k,k+1,t) + p(k, k+2,t)
% upgrade porb:   u(k,t) = p(k,k-1,t) + p(k, k-2,t)
% except for the extreme categories, where the number of buckets is one)

DownProb = zeros(TimeLength, RateSize);
for yr = 1: TimeLength
    for rate = 1: RateSize
        if rate == RateSize
            DownProb(yr,rate) = TM(yr, rate, rate+1);
        else
            DownProb(yr,rate) = TM(yr, rate, rate+1)+ TM(yr, rate, rate+2);
        end
    end
end

UpProb = zeros(TimeLength, RateSize-1);
for yr = 1: TimeLength
    for rate = 2: RateSize
        if rate == 2
            UpProb(yr,rate) = TM(yr, rate, rate-1);
        else
            UpProb(yr,rate) = TM(yr, rate, rate-1)+ TM(yr, rate, rate-2);
        end
    end
end
 


% Test for the presence of unit root (non-stationarity)
% Well-known "augmented" Dickey-Fuller test
for i = 1: RateSize
h_down(i) = adftest(DownProb(:,i));
h_up(i) = adftest(UpProb(:,i));
end
% h_GDP = adftest(GDP,'model','TS','Lags',1);
h_GDP = adftest(GDP);
% If stationary in level, then apply Granger-causality testing procedure

% If non-stationary in level, test cointegration. In the case of
% conintegration, we test for causality within framework of an error
% correction representation.



